package util;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.util.Streams;
import java.util.Calendar;


public final class Utilities {

    public static final String LOGIN_MSG = "<H5> You have not logged in. Please click here to login. <a href='login.jsp'>Login</a></H5>";

    protected Utilities() {
    }

    public static String toUTF8(final String s) throws UnsupportedEncodingException {
        return new String(s.getBytes("iso8859-1"), "utf-8");
    }

    public static String toUTF8(final InputStream fin) throws IOException {
        return new String(Streams.asString(fin, "iso8859-1").trim().getBytes("iso8859-1"), "utf-8");
    }

    public static String toISO8859(final String s) throws UnsupportedEncodingException {
        return new String(s.getBytes("utf-8"), "iso8859-1");
    }

    public static boolean isValid(final String s) {
        return s != null && !s.isEmpty();
    }

    public static boolean isInvalid(final String s) {
        return !isValid(s);
    }

    public static java.sql.Date now() {
        return new java.sql.Date(new java.util.Date().getTime());
    }
    
    
    public static java.sql.Date nowIncrementDay(int numOfDay) {
        //Use Calender to get current date and increment the required number of day
        Calendar tempDate = Calendar.getInstance();
        tempDate.add(Calendar.DAY_OF_MONTH, numOfDay);

        return new java.sql.Date(tempDate.getTimeInMillis());
    }
    
    
    public static String isCorrectStaffLogin(HttpSession session) {
        String name = (String) session.getAttribute("username");
        String identity = (String) session.getAttribute("identity");
        if (name == null) {
            return "<H5> You have not logged in. Please click here to login. <a href='login.jsp'>Login</a></H5>";
        }
        if (!identity.equals("admin")) {
            return "<H5>This page is for administrator only!</H5>";
        } else {
            return null;
        }
    }

    public static double getCurrencyRate(String dollar) throws Exception {
        String link = "http://finance.yahoo.com/currency/convert?amt=1&from=HKD&to=" + dollar + "&submit=Convert";
        BufferedReader in = new BufferedReader(new InputStreamReader(new URL(link).openStream()));
        String s = null;
        while ((s = in.readLine()) != null) {
            if (s.contains("<td class=\"yfnc_tabledata1\">")) {
                String[] s1 = s.split("<td class=\"yfnc_tabledata1\">");
                for (int i = 0; i < s1.length; i++) {
                    String line = s1[i].substring(0, s1[i].indexOf("<"));
                    try {
                        double result = Double.parseDouble(line);
                        return result;
                    } catch (NumberFormatException ex) {
                    }
                }
            }
        }
        throw new Exception("No Such Currency Rate!");
    }
    

    public static void close(ResultSet rs, Statement stmt, Connection con) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException ex) {
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException ex) {
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException ex) {
            }
        }
    }

    public static void close(Statement stmt, Connection con) {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException ex) {
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException ex) {
            }
        }
    }

    public static void close(Connection con) {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException ex) {
            }
        }
    }

    public static void close(Closeable close) {
        if (close != null) {
            try {
                close.close();
            } catch (IOException ex) {
                Logger.getLogger(Utilities.class.getName()).log(Level.SEVERE, "close fail", ex);
            }
        }
    }
}